use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        let create = manager
            .create_table(
                Table::create().table(Menu::Table).if_not_exists()
                .col( ColumnDef::new(Menu::Id).integer().not_null().auto_increment().primary_key().comment("id") )
                .col( ColumnDef::new(Menu::Title).string_len(10).not_null().comment("菜单名称") )
                .col( ColumnDef::new(Menu::Name).string_len(30).not_null().comment("路由名称") )
                .col( ColumnDef::new(Menu::Component).string_len(50).comment("组件路径") )
                .col( ColumnDef::new(Menu::Parent).tiny_integer().comment("上级菜单 id") )
                .col( ColumnDef::new(Menu::Level).tiny_integer().not_null().default(0).comment("菜单排序") )
                .col( ColumnDef::new(Menu::Icon).string_len(10).comment("图标名称") )
                // 固定字段
                .col( ColumnDef::new(Menu::Disabled).tiny_unsigned().not_null().default(0).comment("禁用") )
                .col( ColumnDef::new(Menu::CreateUser).integer().not_null().comment("创建人") )
                .col( ColumnDef::new(Menu::UpdateUser).integer().comment("修改人") )
                .col( ColumnDef::new(Menu::CreateTime).timestamp().default(Expr::current_timestamp()).comment("创建时间") )
                .col( ColumnDef::new(Menu::UpdateTime).timestamp().default(Expr::current_timestamp()).extra("on update current_timestamp").comment("更新时间") )
                .to_owned(),
            ).await;
        match create {
            Ok(_f) => {
                let db = manager.get_connection();
                let insert = db.execute_unprepared(r"
                        insert into menu (title, name, parent, level, create_user) values
                        ('系统管理', 'system', null, 10, 1000),
                        ('菜单管理', 'menu', 1, 0, 1000);
                    "
                ).await;
                match insert {
                    Ok(_f) => Ok(()),
                    Err(e) => Err(e)
                }
            },
            Err(e) => Err(e)
        }
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager.drop_table(Table::drop().table(Menu::Table).to_owned()).await
    }
}

#[derive(DeriveIden)]
enum Menu {
    Table,
    Id,
    Title,
    Name,
    Component,
    Parent,
    Level,
    Icon,
    Disabled,
    CreateUser,
    UpdateUser,
    CreateTime,
    UpdateTime
}